const express = require('express');
const { Op, where } = require('sequelize');
const { Category, Course } = require('../../models');
const router = express.Router();
const { categoryFilterBody } = require('../../utils/filter-req');
const { success, failure } = require('../../utils/responses');
const { NotFound } = require('http-errors');
const { Conflict } = require('http-errors');

const getList = async (req) => {
  const { id } = req.params;
  const categories = await Category.findByPk(id);
  if (!categories) {
    throw new NotFound(`ID：${id}不存在`);
  }
  return categories;
};
router.get('/', async (req, res) => {
  try {
    let { name, currentPage, pageSize } = req.query;
    pageSize = Math.abs(Number(pageSize || 10));
    currentPage = Math.abs(Number(currentPage || 1));
    const condition = {
      order: [
        ['rank', 'ASC'],
        ['id', 'ASC'],
      ],
      include: [{ model: Course, as: 'courses' }],
      limit: pageSize,
      offset: (currentPage - 1) * pageSize,
    };

    if (name) {
      condition.where = {
        name: {
          [Op.like]: `%${name}%`,
        },
      };
    }

    const { count, rows } = await Category.findAndCountAll(condition);

    const data = {
      data: rows,
      pagination: {
        total: count,
        currentPage,
        pageSize,
      },
    };
    success({
      res,
      data,
    });
  } catch (error) {
    // 返回错误信息
    failure({ res, error });
  }
});

router.get('/:id', async (req, res) => {
  try {
    const category = await getList(req);
    success({ res, data: category });
  } catch (error) {
    failure({ res, error });
  }
});
router.post('/', async (req, res) => {
  try {
    const body = categoryFilterBody(req.body);
    await Category.create(body);
    //200状态么和201不同， 201表示请求成功并且创建新的资源 更专业
    success({ res, code: 201, message: '创建成功' });
  } catch (error) {
    failure({ res, error, message: '创建失败' });
  }
});
router.delete('/:id', async (req, res) => {
  try {
    const category = await getList(req);
    const count = await Course.count({ where: { categoryId: req.params.id } });

    if (count > 0) {
      throw new Conflict('当前分类有课程，无法删除。');

      // throw BadRequest('当前分类有课程，无法删除')
    }

    //删除
    await category.destroy();
    success({ res, message: '删除成功' });
  } catch (error) {
    failure({ res, error, message: '删除失败' });
  }
});

router.put('/:id', async (req, res) => {
  try {
    const categories = await getList(req);
    const body = categoryFilterBody(req.body);
    await categories.update(body);
    success({ res, message: '更新成功' });
  } catch (error) {
    failure({ res, error });
  }
});

module.exports = router;
